import socket
import time
from threading import Thread


class TcpClient:
    def __init__(self):
        self.conn_state = False  # True代表连接正常 False代表连接异常
        self.socket = socket.socket()

    def create_connect(self, ip, port):
        address = (ip, port)
        try:
            self.socket.connect(address)
            self.conn_state = True
        except (TimeoutError, ConnectionError):
            print("无法连接到主机.....")
        return self.conn_state

    def __del__(self):
        print("TcpClient—obj exit — — — —")
        self.socket.close()

    def get_data(self, data: str):
        if self.conn_state:
            self.send_data(data)
            return self.receive_data()
        else:
            print("连接不正常，无法发送！！！")

    def receive_data(self):
        recv_data = ""
        while True:
            receive_data = self.socket.recv(1024)
            recv_data += receive_data.decode("gbk")
            if recv_data == "":
                break
        print("接收：", recv_data)

    def send_data(self, data):
        self.socket.send(data.encode("gbk"))
        print("发送：", data)


if __name__ == '__main__':
    tcp_obj = TcpClient(("192.168.1.175", 8556))
    time.sleep(3)
    tcp_obj.get_data("aa3301010009010001000108")
